#!coding=utf8
from django.shortcuts import render, HttpResponse ,HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic import View
from django.contrib.auth.hashers import make_password
from django.core.paginator import *
from django.utils.html import mark_safe
import random, time
import psutil


from DjangoCaptcha import Captcha


from .models import UserProfile, EmailVerifyRecord
from xadmin.models import Log
from Assets.models import *
from .forms import *
from utils.email import random_str
from .task import send_email
from utils.constant import ACTIVED


# Create your views here.


class CustomBackend(ModelBackend):
    '''重写登录认证'''
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


def captcha(request):
    seed = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    sa = []
    for i in range(4):
        sa.append(random.choice(seed))
    salt = ''.join(sa)
    ca = Captcha(request)
    ca.words = [salt]
    ca_mode = request.GET.get('mode', 'word').lower()
    assert ca_mode in ['number', 'word', 'four_number']
    ca.mode = ca_mode
    ca.img_width = 100
    ca.img_height = 30
    return ca.display()


class LoginView(View):
    '''登录页面'''
    def get(self, request):
        if request.user.is_authenticated():
            return HttpResponseRedirect('/index')
        else:
            login_form = LoginForm()
            return render(request, 'login.html', {'login_form': login_form})

    def post(self,request):
        ca = Captcha(request)
        code = request.POST.get('code')
        if ca.check(code):
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                username = request.POST.get('username')
                password = request.POST.get('password')
                user = authenticate(username=username,password=password)
                if user.is_active:
                    login(request, user)
                    remember = request.POST.get('remember')
                    if remember == '1':
                        request.session.set_expiry(60*60*24*30)
                    return JsonResponse({'status': 'ok'})
                else:
                    return render(request, 'login.html', context={"login_form": login_form, 'msg': u'用户已被禁止登陆'})
            else:
                return JsonResponse(login_form.errors)
        else:
            return JsonResponse({'code': u'验证码错误'})


class IndexView(View):
    '''主页'''
    def get(self, request):
        if request.user.is_authenticated():
            servers = Server.objects.all().count()
            users = UserProfile.objects.all().count()
            idcs = GeneratorRoom.objects.all().count()
            mem = psutil.virtual_memory()
            total_mem = mem.total / 1000 / 1000 / 1000
            percent_mem = float(psutil.virtual_memory().percent )
            mem = dict()
            mem['total_mem'] = total_mem
            mem['percent_mem'] = percent_mem
            cpu_usage = psutil.cpu_percent()
            iowait = psutil.cpu_times().iowait
            sys = dict()
            sys['cpu_usage'] = cpu_usage
            sys['iowait'] = iowait
            pids = psutil.pids()
            process=dict()
            for pid in pids:
                p = psutil.Process(pid)
                if p.name() == 'redis-server':
                    process['redis'] = pid
                if p.name() == 'mysqld_safe':
                    process['mysql'] = pid
            context = {'servers': servers, 'users': users, 'idcs': idcs, 'index': ACTIVED, 'mem': mem, 'sys': sys, 'proc': process}
            return render(request, 'index.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        mem = psutil.virtual_memory()
        percent_mem = float(psutil.virtual_memory().percent)
        cpu_usage = psutil.cpu_percent()
        iowait = psutil.cpu_times().iowait
        return JsonResponse({'percent_mem': percent_mem, 'cpu_usage': cpu_usage, 'iowait': iowait})


class LogoutView(View):
    '''登出'''
    def get(self, request):
        logout(request)
        return HttpResponseRedirect('/')


class ForgotPasswordView(View):
    def get(self, request):
        return render(request, 'forgot_password.html')


class RetrievePasswordView(View):
    '''找回密码'''
    def post(self, request):
        email = request.POST.get('email')
        # print email
        try:
            user = UserProfile.objects.get(email = email)
            code = random_str(16)
            url = 'http://127.0.0.1:8000/reset/%s' % code
            email_record = EmailVerifyRecord()
            email_record.email = email
            email_record.code = code
            email_record.send_type = 1
            email_record.save()
            send_email.delay(url, email, 1)
        except Exception as e:
            return JsonResponse({'status': 0})
        return JsonResponse({'status': 1})


class ReSetPasswordView(View):
    '''重置密码界面'''
    def get(self, request,code):
        try:
            record_set = EmailVerifyRecord.objects.get(code=code)
        except Exception as e:
            return HttpResponse(status=404)
        return render(request, 'rest.html')
    def post(self, request, code):
        try:
            record_set = EmailVerifyRecord.objects.get(code = code)
            password = request.POST.get('password')
            password = make_password(password=password)
            user = UserProfile.objects.get(email=record_set.email)
            user.password = password
            user.save()
            record_set.delete()
        except Exception as e:
            return JsonResponse({'status': 0})
        return JsonResponse({'status': 1})




